{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "collapsed_sections": [
        "fzjcZ4FHCOb5"
      ],
      "authorship_tag": "ABX9TyPtjTIh2BnxrHodM1T0I1I2",
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU",
    "gpuClass": "premium"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/mrdbourke/tensorflow-deep-learning/blob/main/00_tensorflow_fundamentals.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ielzxn52r2CB"
      },
      "source": [
        "# 00. Getting started with TensorFlow: A guide to the fundamentals\n",
        "\n",
        "## What is TensorFlow?\n",
        "\n",
        "[TensorFlow](https://www.tensorflow.org/) is an open-source end-to-end machine learning library for preprocessing data, modelling data and serving models (getting them into the hands of others).\n",
        "\n",
        "## Why use TensorFlow?\n",
        "\n",
        "Rather than building machine learning and deep learning models from scratch, it's more likely you'll use a library such as TensorFlow. This is because it contains many of the most common machine learning functions you'll want to use.\n",
        "\n",
        "## What we're going to cover\n",
        "\n",
        "TensorFlow is vast. But the main premise is simple: turn data into numbers (tensors) and build machine learning algorithms to find patterns in them.\n",
        "\n",
        "In this notebook we cover some of the most fundamental TensorFlow operations, more specificially:\n",
        "* Introduction to tensors (creating tensors)\n",
        "* Getting information from tensors (tensor attributes)\n",
        "* Manipulating tensors (tensor operations)\n",
        "* Tensors and NumPy\n",
        "* Using @tf.function (a way to speed up your regular Python functions)\n",
        "* Using GPUs with TensorFlow\n",
        "* Exercises to try\n",
        "\n",
        "Things to note:\n",
        "* Many of the conventions here will happen automatically behind the scenes (when you build a model) but it's worth knowing so if you see any of these things, you know what's happening.\n",
        "* For any TensorFlow function you see, it's important to be able to check it out in the documentation, for example, going to the Python API docs for all functions and searching for what you need: https://www.tensorflow.org/api_docs/python/ (don't worry if this seems overwhelming at first, with enough practice, you'll get used to navigating the documentaiton).\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# Create timestamp\n",
        "import datetime\n",
        "\n",
        "print(f\"Notebook last run (end-to-end): {datetime.datetime.now()}\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "PdXtFSY13JWv",
        "outputId": "d12fed68-45db-4e98-f843-d6a0a13ef906"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Notebook last run (end-to-end): 2023-04-25 05:22:53.455288\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VArmDlu06sH0"
      },
      "source": [
        "## Introduction to Tensors\n",
        "\n",
        "If you've ever used NumPy, [tensors](https://www.tensorflow.org/guide/tensor) are kind of like NumPy arrays (we'll see more on this later).\n",
        "\n",
        "For the sake of this notebook and going forward, you can think of a tensor as a multi-dimensional numerical representation (also referred to as n-dimensional, where n can be any number) of something. Where something can be almost anything you can imagine: \n",
        "* It could be numbers themselves (using tensors to represent the price of houses). \n",
        "* It could be an image (using tensors to represent the pixels of an image).\n",
        "* It could be text (using tensors to represent words).\n",
        "* Or it could be some other form of information (or data) you want to represent with numbers.\n",
        "\n",
        "The main difference between tensors and NumPy arrays (also an n-dimensional array of numbers) is that tensors can be used on [GPUs (graphical processing units)](https://blogs.nvidia.com/blog/2009/12/16/whats-the-difference-between-a-cpu-and-a-gpu/) and [TPUs (tensor processing units)](https://en.wikipedia.org/wiki/Tensor_processing_unit). \n",
        "\n",
        "The benefit of being able to run on GPUs and TPUs is faster computation, this means, if we wanted to find patterns in the numerical representations of our data, we can generally find them faster using GPUs and TPUs.\n",
        "\n",
        "Okay, we've been talking enough about tensors, let's see them.\n",
        "\n",
        "The first thing we'll do is import TensorFlow under the common alias `tf`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Z7ieIu8t9ijY",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "01adfd03-921d-4a59-fe89-3d74610adb21"
      },
      "source": [
        "# Import TensorFlow\n",
        "import tensorflow as tf\n",
        "print(tf.__version__) # find the version number (should be 2.x+)"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "2.12.0\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JNtV5t1qz0VP"
      },
      "source": [
        "### Creating Tensors with `tf.constant()`\n",
        "\n",
        "As mentioned before, in general, you usually won't create tensors yourself. This is because TensorFlow has modules built-in (such as [`tf.io`](https://www.tensorflow.org/api_docs/python/tf/io) and [`tf.data`](https://www.tensorflow.org/guide/data)) which are able to read your data sources and automatically convert them to tensors and then later on, neural network models will process these for us.\n",
        "\n",
        "But for now, because we're getting familar with tensors themselves and how to manipulate them, we'll see how we can create them ourselves.\n",
        "\n",
        "We'll begin by using [`tf.constant()`](https://www.tensorflow.org/api_docs/python/tf/constant)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nC7aQgqi0M_Z",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "6756e867-e2b3-4d64-e7b9-b612394a8ecc"
      },
      "source": [
        "# Create a scalar (rank 0 tensor)\n",
        "scalar = tf.constant(7)\n",
        "scalar"
      ],
      "execution_count": 3,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=int32, numpy=7>"
            ]
          },
          "metadata": {},
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "o6fXE5dXkO_3"
      },
      "source": [
        "A scalar is known as a rank 0 tensor. Because it has no dimensions (it's just a number).\n",
        "\n",
        "> 🔑 **Note:** For now, you don't need to know too much about the different ranks of tensors (but we will see more on this later). The important point is knowing tensors can have an unlimited range of dimensions (the exact amount will depend on what data you're representing)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1sgUNKoFkJ21",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b7538913-97b7-4c39-f732-e0dae545ab8d"
      },
      "source": [
        "# Check the number of dimensions of a tensor (ndim stands for number of dimensions)\n",
        "scalar.ndim"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "0"
            ]
          },
          "metadata": {},
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "irtCo2fs0V_o",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ac00aae7-c80f-4450-d824-f6aa9910362b"
      },
      "source": [
        "# Create a vector (more than 0 dimensions)\n",
        "vector = tf.constant([10, 10])\n",
        "vector"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2,), dtype=int32, numpy=array([10, 10], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "7DDc36pvmOse",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "aec326c7-d359-4df9-f64b-62af8fdc2958"
      },
      "source": [
        "# Check the number of dimensions of our vector tensor\n",
        "vector.ndim"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1"
            ]
          },
          "metadata": {},
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HXf5A5360V7A",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4ad29d49-9ed6-4b7a-aed5-bb6cab663556"
      },
      "source": [
        "# Create a matrix (more than 1 dimension)\n",
        "matrix = tf.constant([[10, 7],\n",
        "                      [7, 10]])\n",
        "matrix"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[10,  7],\n",
              "       [ 7, 10]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 7
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Asmn6YghlT6u",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a720f883-9bed-4f83-833a-1e11c4cac29c"
      },
      "source": [
        "matrix.ndim"
      ],
      "execution_count": 8,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "2"
            ]
          },
          "metadata": {},
          "execution_count": 8
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qvQb7RT2s9Te"
      },
      "source": [
        "By default, TensorFlow creates tensors with either an `int32` or `float32` datatype.\n",
        "\n",
        "This is known as [32-bit precision](https://en.wikipedia.org/wiki/Precision_(computer_science) (the higher the number, the more precise the number, the more space it takes up on your computer)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "aEgthLq80V2u",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "77397970-7687-439d-c0dc-81548d2a238e"
      },
      "source": [
        "# Create another matrix and define the datatype\n",
        "another_matrix = tf.constant([[10., 7.],\n",
        "                              [3., 2.],\n",
        "                              [8., 9.]], dtype=tf.float16) # specify the datatype with 'dtype'\n",
        "another_matrix"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2), dtype=float16, numpy=\n",
              "array([[10.,  7.],\n",
              "       [ 3.,  2.],\n",
              "       [ 8.,  9.]], dtype=float16)>"
            ]
          },
          "metadata": {},
          "execution_count": 9
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "v-Y-lXdOlXRg",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e687b22d-f4fb-44b1-8d7f-06276a39d6ff"
      },
      "source": [
        "# Even though another_matrix contains more numbers, its dimensions stay the same\n",
        "another_matrix.ndim"
      ],
      "execution_count": 10,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "2"
            ]
          },
          "metadata": {},
          "execution_count": 10
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "fAy7J6fT0Vwz",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "976ce412-58bb-4604-a8a6-881b8b6e1a67"
      },
      "source": [
        "# How about a tensor? (more than 2 dimensions, although, all of the above items are also technically tensors)\n",
        "tensor = tf.constant([[[1, 2, 3],\n",
        "                       [4, 5, 6]],\n",
        "                      [[7, 8, 9],\n",
        "                       [10, 11, 12]],\n",
        "                      [[13, 14, 15],\n",
        "                       [16, 17, 18]]])\n",
        "tensor"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2, 3), dtype=int32, numpy=\n",
              "array([[[ 1,  2,  3],\n",
              "        [ 4,  5,  6]],\n",
              "\n",
              "       [[ 7,  8,  9],\n",
              "        [10, 11, 12]],\n",
              "\n",
              "       [[13, 14, 15],\n",
              "        [16, 17, 18]]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 11
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "FhIsj108mFOS",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "cf336e60-876d-423d-d8bf-024f794f5b22"
      },
      "source": [
        "tensor.ndim"
      ],
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "3"
            ]
          },
          "metadata": {},
          "execution_count": 12
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w5MGwSpA100u"
      },
      "source": [
        "This is known as a rank 3 tensor (3-dimensions), however a tensor can have an arbitrary (unlimited) amount of dimensions.\n",
        "\n",
        "For example, you might turn a series of images into tensors with shape (224, 224, 3, 32), where:\n",
        "* 224, 224 (the first 2 dimensions) are the height and width of the images in pixels.\n",
        "* 3 is the number of colour channels of the image (red, green blue).\n",
        "* 32 is the batch size (the number of images a neural network sees at any one time).\n",
        "\n",
        "All of the above variables we've created are actually tensors. But you may also hear them referred to as their different names (the ones we gave them):\n",
        "* **scalar**: a single number.\n",
        "* **vector**: a number with direction (e.g. wind speed with direction).\n",
        "* **matrix**: a 2-dimensional array of numbers.\n",
        "* **tensor**: an n-dimensional arrary of numbers (where n can be any number, a 0-dimension tensor is a scalar, a 1-dimension tensor is a vector). \n",
        "\n",
        "To add to the confusion, the terms matrix and tensor are often used interchangably.\n",
        "\n",
        "Going forward since we're using TensorFlow, everything we refer to and use will be tensors.\n",
        "\n",
        "For more on the mathematical difference between scalars, vectors and matrices see the [visual algebra post by Math is Fun](https://www.mathsisfun.com/algebra/scalar-vector-matrix.html).\n",
        "\n",
        "![difference between scalar, vector, matrix, tensor](https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/images/00-scalar-vector-matrix-tensor.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TZMfDFKC0Cl7"
      },
      "source": [
        "### Creating Tensors with `tf.Variable()`\n",
        "\n",
        "You can also (although you likely rarely will, because often, when working with data, tensors are created for you automatically) create tensors using [`tf.Variable()`](https://www.tensorflow.org/api_docs/python/tf/Variable).\n",
        "\n",
        "The difference between `tf.Variable()` and `tf.constant()` is tensors created with `tf.constant()` are immutable (can't be changed, can only be used to create a new tensor), where as, tensors created with `tf.Variable()` are mutable (can be changed)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bv1SBbDe4TxN",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0aeb31ea-808d-4dc3-bcd3-8ef01be56012"
      },
      "source": [
        "# Create the same tensor with tf.Variable() and tf.constant()\n",
        "changeable_tensor = tf.Variable([10, 7])\n",
        "unchangeable_tensor = tf.constant([10, 7])\n",
        "changeable_tensor, unchangeable_tensor"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([10,  7], dtype=int32)>,\n",
              " <tf.Tensor: shape=(2,), dtype=int32, numpy=array([10,  7], dtype=int32)>)"
            ]
          },
          "metadata": {},
          "execution_count": 13
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "A4WrQ8c2ux15"
      },
      "source": [
        "Now let's try to change one of the elements of the changable tensor."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "dfDwbF6i5Sy3",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 204
        },
        "outputId": "9b25dd77-24c4-4f59-82bb-8f8ae826c384"
      },
      "source": [
        "# Will error (requires the .assign() method)\n",
        "changeable_tensor[0] = 7\n",
        "changeable_tensor"
      ],
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "error",
          "ename": "TypeError",
          "evalue": "ignored",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-14-daecfbad2415>\u001b[0m in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# Will error (requires the .assign() method)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mchangeable_tensor\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m7\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      3\u001b[0m \u001b[0mchangeable_tensor\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mTypeError\u001b[0m: 'ResourceVariable' object does not support item assignment"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oWP-kZEVvGm8"
      },
      "source": [
        "To change an element of a `tf.Variable()` tensor requires the `assign()` method."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "FJV3iwvG4jg4",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "48fac542-e9c3-4d20-9a9a-807accfec61e"
      },
      "source": [
        "# Won't error\n",
        "changeable_tensor[0].assign(7)\n",
        "changeable_tensor"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([7, 7], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 15
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9UiV1Z0XvZ_B"
      },
      "source": [
        "Now let's try to change a value in a `tf.constant()` tensor."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5j_rOo8X5N9f",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 329
        },
        "outputId": "5ccb2e96-6f3e-4bc1-d972-57654a52d6e6"
      },
      "source": [
        "# Will error (can't change tf.constant())\n",
        "unchangeable_tensor[0].assign(7)\n",
        "unchangleable_tensor"
      ],
      "execution_count": 16,
      "outputs": [
        {
          "output_type": "error",
          "ename": "AttributeError",
          "evalue": "ignored",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-16-3947b974feb9>\u001b[0m in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# Will error (can't change tf.constant())\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0munchangeable_tensor\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0massign\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m7\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      3\u001b[0m \u001b[0munchangleable_tensor\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.9/dist-packages/tensorflow/python/framework/ops.py\u001b[0m in \u001b[0;36m__getattr__\u001b[0;34m(self, name)\u001b[0m\n\u001b[1;32m    441\u001b[0m         \u001b[0mnp_config\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0menable_numpy_behavior\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    442\u001b[0m       \"\"\")\n\u001b[0;32m--> 443\u001b[0;31m     \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__getattribute__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    444\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    445\u001b[0m   \u001b[0;34m@\u001b[0m\u001b[0mstaticmethod\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mAttributeError\u001b[0m: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1t21IcYpverQ"
      },
      "source": [
        "Which one should you use? `tf.constant()` or `tf.Variable()`?\n",
        "\n",
        "It will depend on what your problem requires. However, most of the time, TensorFlow will automatically choose for you (when loading data or modelling data)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pAAT59Ay0J0l"
      },
      "source": [
        "### Creating random tensors\n",
        "\n",
        "Random tensors are tensors of some abitrary size which contain random numbers.\n",
        "\n",
        "Why would you want to create random tensors? \n",
        "\n",
        "This is what neural networks use to intialize their weights (patterns) that they're trying to learn in the data.\n",
        "\n",
        "For example, the process of a neural network learning often involves taking a random n-dimensional array of numbers and refining them until they represent some kind of pattern (a compressed way to represent the original data).\n",
        "\n",
        "**How a network learns**\n",
        "![how a network learns](https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/images/00-how-a-network-learns.png)\n",
        "*A network learns by starting with random patterns (1) then going through demonstrative examples of data (2) whilst trying to update its random patterns to represent the examples (3).*\n",
        "\n",
        "We can create random tensors by using the [`tf.random.Generator`](https://www.tensorflow.org/guide/random_numbers#the_tfrandomgenerator_class) class."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yZ7Zu5Z178JL",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "141a772a-635f-4f40-e039-e5c9c4b6c446"
      },
      "source": [
        "# Create two random (but the same) tensors\n",
        "random_1 = tf.random.Generator.from_seed(42) # set the seed for reproducibility\n",
        "random_1 = random_1.normal(shape=(3, 2)) # create tensor from a normal distribution \n",
        "random_2 = tf.random.Generator.from_seed(42)\n",
        "random_2 = random_2.normal(shape=(3, 2))\n",
        "\n",
        "# Are they equal?\n",
        "random_1, random_2, random_1 == random_2"
      ],
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(<tf.Tensor: shape=(3, 2), dtype=float32, numpy=\n",
              " array([[-0.7565803 , -0.06854702],\n",
              "        [ 0.07595026, -1.2573844 ],\n",
              "        [-0.23193765, -1.8107855 ]], dtype=float32)>,\n",
              " <tf.Tensor: shape=(3, 2), dtype=float32, numpy=\n",
              " array([[-0.7565803 , -0.06854702],\n",
              "        [ 0.07595026, -1.2573844 ],\n",
              "        [-0.23193765, -1.8107855 ]], dtype=float32)>,\n",
              " <tf.Tensor: shape=(3, 2), dtype=bool, numpy=\n",
              " array([[ True,  True],\n",
              "        [ True,  True],\n",
              "        [ True,  True]])>)"
            ]
          },
          "metadata": {},
          "execution_count": 17
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "k6Od5fpZ-S--"
      },
      "source": [
        "The random tensors we've made are actually [pseudorandom numbers](https://www.computerhope.com/jargon/p/pseudo-random.htm) (they appear as random, but really aren't).\n",
        "\n",
        "If we set a seed we'll get the same random numbers (if you've ever used NumPy, this is similar to `np.random.seed(42)`). \n",
        "\n",
        "Setting the seed says, \"hey, create some random numbers, but flavour them with X\" (X is the seed).\n",
        "\n",
        "What do you think will happen when we change the seed?"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "9eStLqr1F4ZP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "9b944c3b-37cf-4196-a3be-314d25d16bc0"
      },
      "source": [
        "# Create two random (and different) tensors\n",
        "random_3 = tf.random.Generator.from_seed(42)\n",
        "random_3 = random_3.normal(shape=(3, 2))\n",
        "random_4 = tf.random.Generator.from_seed(11)\n",
        "random_4 = random_4.normal(shape=(3, 2))\n",
        "\n",
        "# Check the tensors and see if they are equal\n",
        "random_3, random_4, random_1 == random_3, random_3 == random_4"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(<tf.Tensor: shape=(3, 2), dtype=float32, numpy=\n",
              " array([[-0.7565803 , -0.06854702],\n",
              "        [ 0.07595026, -1.2573844 ],\n",
              "        [-0.23193765, -1.8107855 ]], dtype=float32)>,\n",
              " <tf.Tensor: shape=(3, 2), dtype=float32, numpy=\n",
              " array([[ 0.2730574 , -0.29925638],\n",
              "        [-0.3652325 ,  0.61883307],\n",
              "        [-1.0130816 ,  0.2829171 ]], dtype=float32)>,\n",
              " <tf.Tensor: shape=(3, 2), dtype=bool, numpy=\n",
              " array([[ True,  True],\n",
              "        [ True,  True],\n",
              "        [ True,  True]])>,\n",
              " <tf.Tensor: shape=(3, 2), dtype=bool, numpy=\n",
              " array([[False, False],\n",
              "        [False, False],\n",
              "        [False, False]])>)"
            ]
          },
          "metadata": {},
          "execution_count": 18
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Nji9AdFRIhBi"
      },
      "source": [
        "What if you wanted to shuffle the order of a tensor?\n",
        "\n",
        "Wait, why would you want to do that?\n",
        "\n",
        "Let's say you working with 15,000 images of cats and dogs and the first 10,000 images of were of cats and the next 5,000 were of dogs. This order could effect how a neural network learns (it may overfit by learning the order of the data), instead, it might be a good idea to move your data around."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "sl4HYEWMBI6x",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "d1c90142-3821-4bd8-da50-f0e3e50ff669"
      },
      "source": [
        "# Shuffle a tensor (valuable for when you want to shuffle your data)\n",
        "not_shuffled = tf.constant([[10, 7],\n",
        "                            [3, 4],\n",
        "                            [2, 5]])\n",
        "# Gets different results each time\n",
        "tf.random.shuffle(not_shuffled)"
      ],
      "execution_count": 19,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n",
              "array([[ 2,  5],\n",
              "       [ 3,  4],\n",
              "       [10,  7]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 19
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-HYn0ME_H1SY",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3e8e6b9b-a28e-45bb-9c21-17e77a1e8375"
      },
      "source": [
        "# Shuffle in the same order every time using the seed parameter (won't acutally be the same)\n",
        "tf.random.shuffle(not_shuffled, seed=42)"
      ],
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n",
              "array([[ 2,  5],\n",
              "       [ 3,  4],\n",
              "       [10,  7]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 20
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GmC3qGIHjAx6"
      },
      "source": [
        "Wait... why didn't the numbers come out the same?\n",
        "\n",
        "It's due to rule #4 of the [`tf.random.set_seed()`](https://www.tensorflow.org/api_docs/python/tf/random/set_seed) documentation.\n",
        "\n",
        "> \"4. If both the global and the operation seed are set: Both seeds are used in conjunction to determine the random sequence.\"\n",
        "\n",
        "`tf.random.set_seed(42)` sets the global seed, and the `seed` parameter in `tf.random.shuffle(seed=42)` sets the operation seed.\n",
        "\n",
        "Because, \"Operations that rely on a random seed actually derive it from two seeds: the global and operation-level seeds. This sets the global seed.\"\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cM6S8set-ixV",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7a317a6f-eb6f-4586-bfc1-75a3361e7001"
      },
      "source": [
        "# Shuffle in the same order every time\n",
        "\n",
        "# Set the global random seed\n",
        "tf.random.set_seed(42)\n",
        "\n",
        "# Set the operation random seed\n",
        "tf.random.shuffle(not_shuffled, seed=42)"
      ],
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n",
              "array([[10,  7],\n",
              "       [ 3,  4],\n",
              "       [ 2,  5]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 21
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xKJOsdE8yCn4",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7ad377d3-b812-4d32-d7dc-8caa5503cc3c"
      },
      "source": [
        "# Set the global random seed\n",
        "tf.random.set_seed(42) # if you comment this out you'll get different results\n",
        "\n",
        "# Set the operation random seed\n",
        "tf.random.shuffle(not_shuffled)"
      ],
      "execution_count": 22,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n",
              "array([[ 3,  4],\n",
              "       [ 2,  5],\n",
              "       [10,  7]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 22
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ouZ1fpJk0R3h"
      },
      "source": [
        "### Other ways to make tensors\n",
        "\n",
        "Though you might rarely use these (remember, many tensor operations are done behind the scenes for you), you can use [`tf.ones()`](https://www.tensorflow.org/api_docs/python/tf/ones) to create a tensor of all ones and [`tf.zeros()`](https://www.tensorflow.org/api_docs/python/tf/zeros) to create a tensor of all zeros."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "aG8QNZP7kEe1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "5701ac23-b90d-4529-bef1-03c2f214dc97"
      },
      "source": [
        "# Make a tensor of all ones\n",
        "tf.ones(shape=(3, 2))"
      ],
      "execution_count": 23,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2), dtype=float32, numpy=\n",
              "array([[1., 1.],\n",
              "       [1., 1.],\n",
              "       [1., 1.]], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 23
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "GQKiWrB9kprj",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0edaf3af-e038-4a58-beeb-69d11f208a17"
      },
      "source": [
        "# Make a tensor of all zeros\n",
        "tf.zeros(shape=(3, 2))"
      ],
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 2), dtype=float32, numpy=\n",
              "array([[0., 0.],\n",
              "       [0., 0.],\n",
              "       [0., 0.]], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 24
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "slcLTK5D7kc2"
      },
      "source": [
        "You can also turn NumPy arrays in into tensors.\n",
        "\n",
        "Remember, the main difference between tensors and NumPy arrays is that tensors can be run on GPUs.\n",
        "\n",
        "> 🔑 **Note:** A matrix or tensor is typically represented by a capital letter (e.g. `X` or `A`) where as a vector is typically represented by a lowercase letter (e.g. `y` or `b`)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "C0XP37xi7mn4",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "eeab31d5-7017-44a9-8543-c86a3f1be67e"
      },
      "source": [
        "import numpy as np\n",
        "numpy_A = np.arange(1, 25, dtype=np.int32) # create a NumPy array between 1 and 25\n",
        "A = tf.constant(numpy_A,  \n",
        "                shape=[2, 4, 3]) # note: the shape total (2*4*3) has to match the number of elements in the array\n",
        "numpy_A, A"
      ],
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,\n",
              "        18, 19, 20, 21, 22, 23, 24], dtype=int32),\n",
              " <tf.Tensor: shape=(2, 4, 3), dtype=int32, numpy=\n",
              " array([[[ 1,  2,  3],\n",
              "         [ 4,  5,  6],\n",
              "         [ 7,  8,  9],\n",
              "         [10, 11, 12]],\n",
              " \n",
              "        [[13, 14, 15],\n",
              "         [16, 17, 18],\n",
              "         [19, 20, 21],\n",
              "         [22, 23, 24]]], dtype=int32)>)"
            ]
          },
          "metadata": {},
          "execution_count": 25
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "J1JLXa2P0wpx"
      },
      "source": [
        "## Getting information from tensors (shape, rank, size)\n",
        "\n",
        "There will be times when you'll want to get different pieces of information from your tensors, in particuluar, you should know the following tensor vocabulary:\n",
        "* **Shape:** The length (number of elements) of each of the dimensions of a tensor.\n",
        "* **Rank:** The number of tensor dimensions. A scalar has rank 0, a vector has rank 1, a matrix is rank 2, a tensor has rank n.\n",
        "* **Axis** or **Dimension:** A particular dimension of a tensor.\n",
        "* **Size:** The total number of items in the tensor.\n",
        "\n",
        "You'll use these especially when you're trying to line up the shapes of your data to the shapes of your model. For example, making sure the shape of your image tensors are the same shape as your models input layer.\n",
        "\n",
        "We've already seen one of these before using the `ndim` attribute. Let's see the rest."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qhckrmovCaAA",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "96ce1206-537e-46fd-80cb-53ac64a9bd01"
      },
      "source": [
        "# Create a rank 4 tensor (4 dimensions)\n",
        "rank_4_tensor = tf.zeros([2, 3, 4, 5])\n",
        "rank_4_tensor"
      ],
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 3, 4, 5), dtype=float32, numpy=\n",
              "array([[[[0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.]],\n",
              "\n",
              "        [[0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.]],\n",
              "\n",
              "        [[0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.]]],\n",
              "\n",
              "\n",
              "       [[[0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.]],\n",
              "\n",
              "        [[0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.]],\n",
              "\n",
              "        [[0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.],\n",
              "         [0., 0., 0., 0., 0.]]]], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 26
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ImJdhWnLtZ_2",
        "outputId": "6527a79f-7b77-43cb-b44a-79c8cc5cd75b"
      },
      "source": [
        "rank_4_tensor.shape, rank_4_tensor.ndim, tf.size(rank_4_tensor)"
      ],
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(TensorShape([2, 3, 4, 5]), 4, <tf.Tensor: shape=(), dtype=int32, numpy=120>)"
            ]
          },
          "metadata": {},
          "execution_count": 27
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Vvb-4ZYdpI9f",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "09edd4f3-49ec-4a3a-9464-f1f9e4da4b81"
      },
      "source": [
        "# Get various attributes of tensor\n",
        "print(\"Datatype of every element:\", rank_4_tensor.dtype)\n",
        "print(\"Number of dimensions (rank):\", rank_4_tensor.ndim)\n",
        "print(\"Shape of tensor:\", rank_4_tensor.shape)\n",
        "print(\"Elements along axis 0 of tensor:\", rank_4_tensor.shape[0])\n",
        "print(\"Elements along last axis of tensor:\", rank_4_tensor.shape[-1])\n",
        "print(\"Total number of elements (2*3*4*5):\", tf.size(rank_4_tensor).numpy()) # .numpy() converts to NumPy array"
      ],
      "execution_count": 28,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Datatype of every element: <dtype: 'float32'>\n",
            "Number of dimensions (rank): 4\n",
            "Shape of tensor: (2, 3, 4, 5)\n",
            "Elements along axis 0 of tensor: 2\n",
            "Elements along last axis of tensor: 5\n",
            "Total number of elements (2*3*4*5): 120\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S0SMO2ZOqL0G"
      },
      "source": [
        "You can also index tensors just like Python lists."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "CFzOo-7QqLJf",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "144077a7-5855-4df9-f7c1-219a80fe5274"
      },
      "source": [
        "# Get the first 2 items of each dimension\n",
        "rank_4_tensor[:2, :2, :2, :2]"
      ],
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2, 2, 2), dtype=float32, numpy=\n",
              "array([[[[0., 0.],\n",
              "         [0., 0.]],\n",
              "\n",
              "        [[0., 0.],\n",
              "         [0., 0.]]],\n",
              "\n",
              "\n",
              "       [[[0., 0.],\n",
              "         [0., 0.]],\n",
              "\n",
              "        [[0., 0.],\n",
              "         [0., 0.]]]], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 29
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "weQe2bBUqknd",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0d035e40-a245-4655-f334-8875ad0309a4"
      },
      "source": [
        "# Get the dimension from each index except for the final one\n",
        "rank_4_tensor[:1, :1, :1, :]"
      ],
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(1, 1, 1, 5), dtype=float32, numpy=array([[[[0., 0., 0., 0., 0.]]]], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 30
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YQKcZWz5rFXG",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1993c0f6-e742-4cfc-bfc9-d9c344250e34"
      },
      "source": [
        "# Create a rank 2 tensor (2 dimensions)\n",
        "rank_2_tensor = tf.constant([[10, 7],\n",
        "                             [3, 4]])\n",
        "\n",
        "# Get the last item of each row\n",
        "rank_2_tensor[:, -1]"
      ],
      "execution_count": 31,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2,), dtype=int32, numpy=array([7, 4], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 31
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cLZq3sHKrVdS"
      },
      "source": [
        "You can also add dimensions to your tensor whilst keeping the same information present using `tf.newaxis`. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KuEEEQa4w1id",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "c5ab97d4-7a4d-4db9-8d6d-9a99970b6b1e"
      },
      "source": [
        "# Add an extra dimension (to the end)\n",
        "rank_3_tensor = rank_2_tensor[..., tf.newaxis] # in Python \"...\" means \"all dimensions prior to\"\n",
        "rank_2_tensor, rank_3_tensor # shape (2, 2), shape (2, 2, 1)"
      ],
      "execution_count": 32,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              " array([[10,  7],\n",
              "        [ 3,  4]], dtype=int32)>,\n",
              " <tf.Tensor: shape=(2, 2, 1), dtype=int32, numpy=\n",
              " array([[[10],\n",
              "         [ 7]],\n",
              " \n",
              "        [[ 3],\n",
              "         [ 4]]], dtype=int32)>)"
            ]
          },
          "metadata": {},
          "execution_count": 32
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "a5_KyB-6r7z7"
      },
      "source": [
        "You can achieve the same using [`tf.expand_dims()`](https://www.tensorflow.org/api_docs/python/tf/expand_dims)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HpPTBqt4rvr9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "925068e5-f544-45c3-be1a-7be9fbca22a6"
      },
      "source": [
        "tf.expand_dims(rank_2_tensor, axis=-1) # \"-1\" means last axis"
      ],
      "execution_count": 33,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2, 1), dtype=int32, numpy=\n",
              "array([[[10],\n",
              "        [ 7]],\n",
              "\n",
              "       [[ 3],\n",
              "        [ 4]]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 33
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4EHae9iA04Ok"
      },
      "source": [
        "## Manipulating tensors (tensor operations)\n",
        "\n",
        "Finding patterns in tensors (numberical representation of data) requires manipulating them.\n",
        "\n",
        "Again, when building models in TensorFlow, much of this pattern discovery is done for you."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-NzdbYDqs1Ex"
      },
      "source": [
        "### Basic operations\n",
        "\n",
        "You can perform many of the basic mathematical operations directly on tensors using Pyhton operators such as, `+`, `-`, `*`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tu3zJirLsMVw",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "900fe49b-d098-4082-b9df-fa274e6d0739"
      },
      "source": [
        "# You can add values to a tensor using the addition operator\n",
        "tensor = tf.constant([[10, 7], [3, 4]])\n",
        "tensor + 10"
      ],
      "execution_count": 34,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[20, 17],\n",
              "       [13, 14]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 34
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_smxbIkYwYY3"
      },
      "source": [
        "Since we used `tf.constant()`, the original tensor is unchanged (the addition gets done on a copy)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BhJn3puhwOlM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "711d938f-ddd4-4999-f667-dc2e80d4b70a"
      },
      "source": [
        "# Original tensor unchanged\n",
        "tensor"
      ],
      "execution_count": 35,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[10,  7],\n",
              "       [ 3,  4]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 35
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5N6tUM16xq9d"
      },
      "source": [
        "Other operators also work."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6TW0_ZC_xoEC",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7042cd55-6025-430e-95bb-a9cce80eafd1"
      },
      "source": [
        "# Multiplication (known as element-wise multiplication)\n",
        "tensor * 10"
      ],
      "execution_count": 36,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[100,  70],\n",
              "       [ 30,  40]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 36
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "MN6XjwWfxu66",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ab56a5c4-52f1-41e9-c162-8d3edb5ff73f"
      },
      "source": [
        "# Subtraction\n",
        "tensor - 10"
      ],
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[ 0, -3],\n",
              "       [-7, -6]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 37
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1kMJe4GlyuZR"
      },
      "source": [
        "You can also use the equivalent TensorFlow function. Using the TensorFlow function (where possible) has the advantage of being sped up later down the line when running as part of a [TensorFlow graph](https://www.tensorflow.org/tensorboard/graphs)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "R2NDjqYIyyMc",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "bb357174-e7df-41f3-e6cc-622efd029a07"
      },
      "source": [
        "# Use the tensorflow function equivalent of the '*' (multiply) operator\n",
        "tf.multiply(tensor, 10)"
      ],
      "execution_count": 38,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[100,  70],\n",
              "       [ 30,  40]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 38
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lKEuDBFD49w7",
        "outputId": "270b64c8-424f-4c3b-84ce-24ba156cd147"
      },
      "source": [
        "# The original tensor is still unchanged\n",
        "tensor"
      ],
      "execution_count": 39,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[10,  7],\n",
              "       [ 3,  4]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 39
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8M-0dhjtzHoZ"
      },
      "source": [
        "### Matrix mutliplication\n",
        "\n",
        "One of the most common operations in machine learning algorithms is [matrix multiplication](https://www.mathsisfun.com/algebra/matrix-multiplying.html).\n",
        "\n",
        "TensorFlow implements this matrix multiplication functionality in the [`tf.matmul()`](https://www.tensorflow.org/api_docs/python/tf/linalg/matmul) method.\n",
        "\n",
        "The main two rules for matrix multiplication to remember are:\n",
        "1. The inner dimensions must match:\n",
        "  * `(3, 5) @ (3, 5)` won't work\n",
        "  * `(5, 3) @ (3, 5)` will work\n",
        "  * `(3, 5) @ (5, 3)` will work\n",
        "2. The resulting matrix has the shape of the outer dimensions:\n",
        " * `(5, 3) @ (3, 5)` -> `(5, 5)`\n",
        " * `(3, 5) @ (5, 3)` -> `(3, 3)`\n",
        "\n",
        "> 🔑 **Note:** '`@`' in Python is the symbol for matrix multiplication."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "pbpwVJrAsPpA",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "58f18b51-6fd4-4af1-e74b-ee8f06611a7c"
      },
      "source": [
        "# Matrix multiplication in TensorFlow\n",
        "print(tensor)\n",
        "tf.matmul(tensor, tensor)"
      ],
      "execution_count": 40,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "tf.Tensor(\n",
            "[[10  7]\n",
            " [ 3  4]], shape=(2, 2), dtype=int32)\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[121,  98],\n",
              "       [ 42,  37]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 40
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "9vpDnpb10G7U",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "02039aad-06e1-4589-fe91-f65870716ba7"
      },
      "source": [
        "# Matrix multiplication with Python operator '@'\n",
        "tensor @ tensor"
      ],
      "execution_count": 41,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[121,  98],\n",
              "       [ 42,  37]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 41
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TAV3S5YV0cDQ"
      },
      "source": [
        "Both of these examples work because our `tensor` variable is of shape (2, 2).\n",
        "\n",
        "What if we created some tensors which had mismatched shapes?"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "UXSE6q1o0amm",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2f106764-d526-44a6-e1e9-255aa3c4a83e"
      },
      "source": [
        "# Create (3, 2) tensor\n",
        "X = tf.constant([[1, 2],\n",
        "                 [3, 4],\n",
        "                 [5, 6]])\n",
        "\n",
        "# Create another (3, 2) tensor\n",
        "Y = tf.constant([[7, 8],\n",
        "                 [9, 10],\n",
        "                 [11, 12]])\n",
        "X, Y"
      ],
      "execution_count": 42,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(<tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n",
              " array([[1, 2],\n",
              "        [3, 4],\n",
              "        [5, 6]], dtype=int32)>,\n",
              " <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n",
              " array([[ 7,  8],\n",
              "        [ 9, 10],\n",
              "        [11, 12]], dtype=int32)>)"
            ]
          },
          "metadata": {},
          "execution_count": 42
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "3J4DGQa309Hc",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 336
        },
        "outputId": "a3ee6031-1c27-4089-8db2-db0867160008"
      },
      "source": [
        "# Try to matrix multiply them (will error)\n",
        "X @ Y"
      ],
      "execution_count": 43,
      "outputs": [
        {
          "output_type": "error",
          "ename": "InvalidArgumentError",
          "evalue": "ignored",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mInvalidArgumentError\u001b[0m                      Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-43-62e1e4702ffd>\u001b[0m in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# Try to matrix multiply them (will error)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mX\u001b[0m \u001b[0;34m@\u001b[0m \u001b[0mY\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;32m/usr/local/lib/python3.9/dist-packages/tensorflow/python/util/traceback_utils.py\u001b[0m in \u001b[0;36merror_handler\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m    151\u001b[0m     \u001b[0;32mexcept\u001b[0m \u001b[0mException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    152\u001b[0m       \u001b[0mfiltered_tb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_process_traceback_frames\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__traceback__\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 153\u001b[0;31m       \u001b[0;32mraise\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwith_traceback\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfiltered_tb\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    154\u001b[0m     \u001b[0;32mfinally\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    155\u001b[0m       \u001b[0;32mdel\u001b[0m \u001b[0mfiltered_tb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.9/dist-packages/tensorflow/python/framework/ops.py\u001b[0m in \u001b[0;36mraise_from_not_ok_status\u001b[0;34m(e, name)\u001b[0m\n\u001b[1;32m   7260\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mraise_from_not_ok_status\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mname\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   7261\u001b[0m   \u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmessage\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\" name: \"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mname\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mname\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m \u001b[0;32melse\u001b[0m \u001b[0;34m\"\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 7262\u001b[0;31m   \u001b[0;32mraise\u001b[0m \u001b[0mcore\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_status_to_exception\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;32mNone\u001b[0m  \u001b[0;31m# pylint: disable=protected-access\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   7263\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   7264\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mInvalidArgumentError\u001b[0m: {{function_node __wrapped__MatMul_device_/job:localhost/replica:0/task:0/device:CPU:0}} Matrix size-incompatible: In[0]: [3,2], In[1]: [3,2] [Op:MatMul]"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "v27FQ59v1N-H"
      },
      "source": [
        "Trying to matrix multiply two tensors with the shape `(3, 2)` errors because the inner dimensions don't match.\n",
        "\n",
        "We need to either:\n",
        "* Reshape X to `(2, 3)` so it's `(2, 3) @ (3, 2)`.\n",
        "* Reshape Y to `(3, 2)` so it's `(3, 2) @ (2, 3)`.\n",
        "\n",
        "We can do this with either:\n",
        "* [`tf.reshape()`](https://www.tensorflow.org/api_docs/python/tf/reshape) - allows us to reshape a tensor into a defined shape.\n",
        "* [`tf.transpose()`](https://www.tensorflow.org/api_docs/python/tf/transpose) - switches the dimensions of a given tensor.\n",
        "\n",
        "![lining up dimensions for dot products](https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/images/00-lining-up-dot-products.png)\n",
        "\n",
        "Let's try `tf.reshape()` first."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ZwvVl-k_2W9u",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "86025237-4258-4582-8a62-d36f29f281fc"
      },
      "source": [
        "# Example of reshape (3, 2) -> (2, 3)\n",
        "tf.reshape(Y, shape=(2, 3))"
      ],
      "execution_count": 44,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n",
              "array([[ 7,  8,  9],\n",
              "       [10, 11, 12]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 44
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1jBKPQVn1Nep",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "83040cf0-d09f-4e61-f9d5-bc5556492fdb"
      },
      "source": [
        "# Try matrix multiplication with reshaped Y\n",
        "X @ tf.reshape(Y, shape=(2, 3))"
      ],
      "execution_count": 45,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 3), dtype=int32, numpy=\n",
              "array([[ 27,  30,  33],\n",
              "       [ 61,  68,  75],\n",
              "       [ 95, 106, 117]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 45
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CWAgHKNk2_TO"
      },
      "source": [
        "It worked, let's try the same with a reshaped `X`, except this time we'll use [`tf.transpose()`](https://www.tensorflow.org/api_docs/python/tf/transpose) and `tf.matmul()`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qA2rCnik2OnQ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f26d252c-8fed-445b-e0a3-b51de62ec7b0"
      },
      "source": [
        "# Example of transpose (3, 2) -> (2, 3)\n",
        "tf.transpose(X)"
      ],
      "execution_count": 46,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n",
              "array([[1, 3, 5],\n",
              "       [2, 4, 6]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 46
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zR8YdMfh3G0S",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "468e80ff-8708-4ff9-93bd-9bc614004039"
      },
      "source": [
        "# Try matrix multiplication \n",
        "tf.matmul(tf.transpose(X), Y)"
      ],
      "execution_count": 47,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[ 89,  98],\n",
              "       [116, 128]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 47
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "SL45P1cC5tnJ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2ffe20dd-3a85-4dc9-98e3-01bd973df267"
      },
      "source": [
        "# You can achieve the same result with parameters\n",
        "tf.matmul(a=X, b=Y, transpose_a=True, transpose_b=False)"
      ],
      "execution_count": 48,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[ 89,  98],\n",
              "       [116, 128]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 48
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AqE518TJ3GXG"
      },
      "source": [
        "Notice the difference in the resulting shapes when tranposing `X` or reshaping `Y`.\n",
        "\n",
        "This is because of the 2nd rule mentioned above:\n",
        " * `(3, 2) @ (2, 3)` -> `(3, 3)` done with `X @ tf.reshape(Y, shape=(2, 3))` \n",
        " * `(2, 3) @ (3, 2)` -> `(2, 2)` done with `tf.matmul(tf.transpose(X), Y)`\n",
        "\n",
        "This kind of data manipulation is a reminder: you'll spend a lot of your time in machine learning and working with neural networks reshaping data (in the form of tensors) to prepare it to be used with various operations (such as feeding it to a model).\n",
        "\n",
        "### The dot product\n",
        "\n",
        "Multiplying matrices by eachother is also referred to as the dot product.\n",
        "\n",
        "You can perform the `tf.matmul()` operation using [`tf.tensordot()`](https://www.tensorflow.org/api_docs/python/tf/tensordot). "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qfSJHDpe2Oe9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b128a9eb-0e98-4379-b9d2-e0d29edd86f9"
      },
      "source": [
        "# Perform the dot product on X and Y (requires X to be transposed)\n",
        "tf.tensordot(tf.transpose(X), Y, axes=1)"
      ],
      "execution_count": 49,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n",
              "array([[ 89,  98],\n",
              "       [116, 128]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 49
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "waJcSOGf_Fg7"
      },
      "source": [
        "You might notice that although using both `reshape` and `tranpose` work, you get different results when using each.\n",
        "\n",
        "Let's see an example, first with `tf.transpose()` then with `tf.reshape()`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "AAzB-F4l6Dc0",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "9f656c4e-cd07-4496-9036-3d399ede9006"
      },
      "source": [
        "# Perform matrix multiplication between X and Y (transposed)\n",
        "tf.matmul(X, tf.transpose(Y))"
      ],
      "execution_count": 50,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 3), dtype=int32, numpy=\n",
              "array([[ 23,  29,  35],\n",
              "       [ 53,  67,  81],\n",
              "       [ 83, 105, 127]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 50
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "s-kQH7qh69PV",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "02a9e262-7405-4454-87e0-c86bc9d352be"
      },
      "source": [
        "# Perform matrix multiplication between X and Y (reshaped)\n",
        "tf.matmul(X, tf.reshape(Y, (2, 3)))"
      ],
      "execution_count": 51,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3, 3), dtype=int32, numpy=\n",
              "array([[ 27,  30,  33],\n",
              "       [ 61,  68,  75],\n",
              "       [ 95, 106, 117]], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 51
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2eCDnCX6AhbF"
      },
      "source": [
        "Hmm... they result in different values.\n",
        "\n",
        "Which is strange because when dealing with `Y` (a `(3x2)` matrix), reshaping to `(2, 3)` and tranposing it result in the same shape."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "P_RLV373ATAb",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "bf406bb5-12f6-4912-88d4-d594870925b8"
      },
      "source": [
        "# Check shapes of Y, reshaped Y and tranposed Y\n",
        "Y.shape, tf.reshape(Y, (2, 3)).shape, tf.transpose(Y).shape"
      ],
      "execution_count": 52,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(TensorShape([3, 2]), TensorShape([2, 3]), TensorShape([2, 3]))"
            ]
          },
          "metadata": {},
          "execution_count": 52
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OilqUMBKAevX"
      },
      "source": [
        "But calling `tf.reshape()` and `tf.transpose()` on `Y` don't necessarily result in the same values."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "B5_aYjqeA_w_",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3467c583-4afa-48ee-d2a6-9ef9bb2e5020"
      },
      "source": [
        "# Check values of Y, reshape Y and tranposed Y\n",
        "print(\"Normal Y:\")\n",
        "print(Y, \"\\n\") # \"\\n\" for newline\n",
        "\n",
        "print(\"Y reshaped to (2, 3):\")\n",
        "print(tf.reshape(Y, (2, 3)), \"\\n\")\n",
        "\n",
        "print(\"Y transposed:\")\n",
        "print(tf.transpose(Y))"
      ],
      "execution_count": 53,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Normal Y:\n",
            "tf.Tensor(\n",
            "[[ 7  8]\n",
            " [ 9 10]\n",
            " [11 12]], shape=(3, 2), dtype=int32) \n",
            "\n",
            "Y reshaped to (2, 3):\n",
            "tf.Tensor(\n",
            "[[ 7  8  9]\n",
            " [10 11 12]], shape=(2, 3), dtype=int32) \n",
            "\n",
            "Y transposed:\n",
            "tf.Tensor(\n",
            "[[ 7  9 11]\n",
            " [ 8 10 12]], shape=(2, 3), dtype=int32)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "g9g3l45LFO7K"
      },
      "source": [
        "As you can see, the outputs of `tf.reshape()` and `tf.transpose()` when called on `Y`, even though they have the same shape, are different.\n",
        "\n",
        "This can be explained by the default behaviour of each method:\n",
        "* [`tf.reshape()`](https://www.tensorflow.org/api_docs/python/tf/reshape) - change the shape of the given tensor (first) and then insert values in order they appear (in our case, 7, 8, 9, 10, 11, 12).\n",
        "* [`tf.transpose()`](https://www.tensorflow.org/api_docs/python/tf/transpose) - swap the order of the axes, by default the last axis becomes the first, however the order can be changed using the [`perm` parameter](https://www.tensorflow.org/api_docs/python/tf/transpose)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fzjcZ4FHCOb5"
      },
      "source": [
        "So which should you use?\n",
        "\n",
        "Again, most of the time these operations (when they need to be run, such as during the training a neural network, will be implemented for you).\n",
        "\n",
        "But generally, whenever performing a matrix multiplication and the shapes of two matrices don't line up, you will transpose (not reshape) one of them in order to line them up.\n",
        "\n",
        "### Matrix multiplication tidbits\n",
        "* If we transposed `Y`, it would be represented as $\\mathbf{Y}^\\mathsf{T}$ (note the capital T for tranpose).\n",
        "* Get an illustrative view of matrix multiplication [by Math is Fun](https://www.mathsisfun.com/algebra/matrix-multiplying.html).\n",
        "* Try a hands-on demo of matrix multiplcation: http://matrixmultiplication.xyz/ (shown below).\n",
        "\n",
        "![visual demo of matrix multiplication](https://raw.githubusercontent.com/mrdbourke/tensorflow-deep-learning/main/images/00-matrix-multiply-crop.gif)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bK8Kc94SL-JL"
      },
      "source": [
        "### Changing the datatype of a tensor\n",
        "\n",
        "Sometimes you'll want to alter the default datatype of your tensor. \n",
        "\n",
        "This is common when you want to compute using less precision (e.g. 16-bit floating point numbers vs. 32-bit floating point numbers). \n",
        "\n",
        "Computing with less precision is useful on devices with less computing capacity such as mobile devices (because the less bits, the less space the computations require).\n",
        "\n",
        "You can change the datatype of a tensor using [`tf.cast()`](https://www.tensorflow.org/api_docs/python/tf/cast)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jRkZhW35Lge_",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "117f9814-e7f2-42ee-ab76-498bbde856f3"
      },
      "source": [
        "# Create a new tensor with default datatype (float32)\n",
        "B = tf.constant([1.7, 7.4])\n",
        "\n",
        "# Create a new tensor with default datatype (int32)\n",
        "C = tf.constant([1, 7])\n",
        "B, C"
      ],
      "execution_count": 54,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.7, 7.4], dtype=float32)>,\n",
              " <tf.Tensor: shape=(2,), dtype=int32, numpy=array([1, 7], dtype=int32)>)"
            ]
          },
          "metadata": {},
          "execution_count": 54
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kdhV1rgcNpUP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "c2293dcd-cfe0-4618-e304-925f16a6db12"
      },
      "source": [
        "# Change from float32 to float16 (reduced precision)\n",
        "B = tf.cast(B, dtype=tf.float16)\n",
        "B"
      ],
      "execution_count": 55,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2,), dtype=float16, numpy=array([1.7, 7.4], dtype=float16)>"
            ]
          },
          "metadata": {},
          "execution_count": 55
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Px2E1ANeNxRv",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a984cf0d-e14e-46db-a6d8-aa300cb121fe"
      },
      "source": [
        "# Change from int32 to float32\n",
        "C = tf.cast(C, dtype=tf.float32)\n",
        "C"
      ],
      "execution_count": 56,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1., 7.], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 56
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1F3L1BDuQVJz"
      },
      "source": [
        "### Getting the absolute value\n",
        "Sometimes you'll want the absolute values (all values are positive) of elements in your tensors.\n",
        "\n",
        "To do so, you can use [`tf.abs()`](https://www.tensorflow.org/api_docs/python/tf/math/abs)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "plNBFi51QOvW",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b82f87c5-ada1-43b5-b998-5d6fa8e90931"
      },
      "source": [
        "# Create tensor with negative values\n",
        "D = tf.constant([-7, -10])\n",
        "D"
      ],
      "execution_count": 57,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2,), dtype=int32, numpy=array([ -7, -10], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 57
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bOSYmX37QFHS",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b80c6fd6-e1b5-469b-ffe8-f654be0be472"
      },
      "source": [
        "# Get the absolute values\n",
        "tf.abs(D)"
      ],
      "execution_count": 58,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(2,), dtype=int32, numpy=array([ 7, 10], dtype=int32)>"
            ]
          },
          "metadata": {},
          "execution_count": 58
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G4cnALehQ2CE"
      },
      "source": [
        "### Finding the min, max, mean, sum (aggregation)\n",
        "\n",
        "You can quickly aggregate (perform a calculation on a whole tensor) tensors to find things like the minimum value, maximum value, mean and sum of all the elements.\n",
        "\n",
        "To do so, aggregation methods typically have the syntax `reduce()_[action]`, such as:\n",
        "* [`tf.reduce_min()`](https://www.tensorflow.org/api_docs/python/tf/math/reduce_min) - find the minimum value in a tensor.\n",
        "* [`tf.reduce_max()`](https://www.tensorflow.org/api_docs/python/tf/math/reduce_max) - find the maximum value in a tensor (helpful for when you want to find the highest prediction probability).\n",
        "* [`tf.reduce_mean()`](https://www.tensorflow.org/api_docs/python/tf/math/reduce_mean) - find the mean of all elements in a tensor.\n",
        "* [`tf.reduce_sum()`](https://www.tensorflow.org/api_docs/python/tf/math/reduce_sum) - find the sum of all elements in a tensor.\n",
        "* **Note:** typically, each of these is under the `math` module, e.g. `tf.math.reduce_min()` but you can use the alias `tf.reduce_min()`.\n",
        "\n",
        "Let's see them in action."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kjW5_6i6Q7oo",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "684c3ac0-753c-4743-ac93-3297e624d0e0"
      },
      "source": [
        "# Create a tensor with 50 random values between 0 and 100\n",
        "E = tf.constant(np.random.randint(low=0, high=100, size=50))\n",
        "E"
      ],
      "execution_count": 59,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(50,), dtype=int64, numpy=\n",
              "array([75, 89, 76, 55, 36, 10, 93, 90, 28, 41, 21,  6, 43, 69, 47, 16, 33,\n",
              "       98, 30, 27, 20, 51,  8, 49, 82, 35, 12, 47, 59, 14, 41, 75, 71,  7,\n",
              "       48, 67, 90, 73, 71,  7,  7, 51, 81, 20, 13, 90, 47, 33, 17, 51])>"
            ]
          },
          "metadata": {},
          "execution_count": 59
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "slwMVgT-Rac0",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "482cd514-c1af-4101-84d7-ddd4c07c4ba7"
      },
      "source": [
        "# Find the minimum\n",
        "tf.reduce_min(E)"
      ],
      "execution_count": 60,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=int64, numpy=6>"
            ]
          },
          "metadata": {},
          "execution_count": 60
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "voLqafGCRYqO",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "de7dd3b5-050e-4dc7-a5b1-e485f7c10d9b"
      },
      "source": [
        "# Find the maximum\n",
        "tf.reduce_max(E)"
      ],
      "execution_count": 61,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=int64, numpy=98>"
            ]
          },
          "metadata": {},
          "execution_count": 61
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "MPqwvy6TRYN3",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4801507a-d568-42d1-aa10-1b3df4d9854b"
      },
      "source": [
        "# Find the mean\n",
        "tf.reduce_mean(E)"
      ],
      "execution_count": 62,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=int64, numpy=46>"
            ]
          },
          "metadata": {},
          "execution_count": 62
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lqwCXeD6RhyE",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0f2a23e2-1381-463e-fb84-d9aad6c3efc1"
      },
      "source": [
        "# Find the sum\n",
        "tf.reduce_sum(E)"
      ],
      "execution_count": 63,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=int64, numpy=2320>"
            ]
          },
          "metadata": {},
          "execution_count": 63
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zXGyiVPiRqgO"
      },
      "source": [
        "You can also find the standard deviation ([`tf.reduce_std()`](https://www.tensorflow.org/api_docs/python/tf/math/reduce_std)) and variance ([`tf.reduce_variance()`](https://www.tensorflow.org/api_docs/python/tf/math/reduce_variance)) of elements in a tensor using similar methods.\n",
        "\n",
        "### Finding the positional maximum and minimum\n",
        "\n",
        "How about finding the position a tensor where the maximum value occurs?\n",
        "\n",
        "This is helpful when you want to line up your labels (say `['Green', 'Blue', 'Red']`) with your prediction probabilities tensor (e.g. `[0.98, 0.01, 0.01]`).\n",
        "\n",
        "In this case, the predicted label (the one with the highest prediction probability) would be `'Green'`.\n",
        "\n",
        "You can do the same for the minimum (if required) with the following:\n",
        "* [`tf.argmax()`](https://www.tensorflow.org/api_docs/python/tf/math/argmax) - find the position of the maximum element in a given tensor.\n",
        "* [`tf.argmin()`](https://www.tensorflow.org/api_docs/python/tf/math/argmin) - find the position of the minimum element in a given tensor."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "PspO0Vjp3Nm6",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e64798b1-ac90-40fc-c820-7b2fcd158b41"
      },
      "source": [
        "# Create a tensor with 50 values between 0 and 1\n",
        "F = tf.constant(np.random.random(50))\n",
        "F"
      ],
      "execution_count": 64,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(50,), dtype=float64, numpy=\n",
              "array([0.08892525, 0.94484011, 0.72484292, 0.11100388, 0.23637676,\n",
              "       0.40758941, 0.78697704, 0.51382876, 0.67817528, 0.33801469,\n",
              "       0.06847686, 0.43940259, 0.05384978, 0.90974966, 0.17755086,\n",
              "       0.55687455, 0.22395101, 0.61040988, 0.19115218, 0.43669498,\n",
              "       0.95362449, 0.65974345, 0.98141608, 0.72890794, 0.31333329,\n",
              "       0.95735583, 0.80562309, 0.08673455, 0.5237697 , 0.9006758 ,\n",
              "       0.07103048, 0.88667591, 0.70505817, 0.79932324, 0.28416341,\n",
              "       0.50271115, 0.2614137 , 0.22194647, 0.96336433, 0.88853101,\n",
              "       0.23221737, 0.92196873, 0.84103254, 0.01333408, 0.24513585,\n",
              "       0.74766312, 0.8508123 , 0.94218343, 0.90917265, 0.78489794])>"
            ]
          },
          "metadata": {},
          "execution_count": 64
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ADbAMm9N3Zlb",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0b16b507-e863-453e-c7e2-75bb44684bd5"
      },
      "source": [
        "# Find the maximum element position of F\n",
        "tf.argmax(F)"
      ],
      "execution_count": 65,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=int64, numpy=22>"
            ]
          },
          "metadata": {},
          "execution_count": 65
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "aQrv1nVE3ckx",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "6e52173e-8f33-4a8a-aff7-ad968f163e92"
      },
      "source": [
        "# Find the minimum element position of F\n",
        "tf.argmin(F)"
      ],
      "execution_count": 66,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(), dtype=int64, numpy=43>"
            ]
          },
          "metadata": {},
          "execution_count": 66
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yFHzARFwLmIf",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e67cf2cc-93f9-44f6-810c-647814d5ba4f"
      },
      "source": [
        "# Find the maximum element position of F\n",
        "print(f\"The maximum value of F is at position: {tf.argmax(F).numpy()}\") \n",
        "print(f\"The maximum value of F is: {tf.reduce_max(F).numpy()}\") \n",
        "print(f\"Using tf.argmax() to index F, the maximum value of F is: {F[tf.argmax(F)].numpy()}\")\n",
        "print(f\"Are the two max values the same (they should be)? {F[tf.argmax(F)].numpy() == tf.reduce_max(F).numpy()}\")"
      ],
      "execution_count": 67,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The maximum value of F is at position: 22\n",
            "The maximum value of F is: 0.9814160834311638\n",
            "Using tf.argmax() to index F, the maximum value of F is: 0.9814160834311638\n",
            "Are the two max values the same (they should be)? True\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vSGIuNwm5QHM"
      },
      "source": [
        "### Squeezing a tensor (removing all single dimensions)\n",
        "\n",
        "If you need to remove single-dimensions from a tensor (dimensions with size 1), you can use `tf.squeeze()`.\n",
        "\n",
        "* [`tf.squeeze()`](https://www.tensorflow.org/api_docs/python/tf/squeeze) - remove all dimensions of 1 from a tensor.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6xDZLtNu5wUZ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a641e1bc-7624-428c-942a-3d51170add8d"
      },
      "source": [
        "# Create a rank 5 (5 dimensions) tensor of 50 numbers between 0 and 100\n",
        "G = tf.constant(np.random.randint(0, 100, 50), shape=(1, 1, 1, 1, 50))\n",
        "G.shape, G.ndim"
      ],
      "execution_count": 68,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(TensorShape([1, 1, 1, 1, 50]), 5)"
            ]
          },
          "metadata": {},
          "execution_count": 68
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "oS91XOgO6lai",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a9635c26-310e-46b0-9d80-604bddf7c8e5"
      },
      "source": [
        "# Squeeze tensor G (remove all 1 dimensions)\n",
        "G_squeezed = tf.squeeze(G)\n",
        "G_squeezed.shape, G_squeezed.ndim"
      ],
      "execution_count": 69,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(TensorShape([50]), 1)"
            ]
          },
          "metadata": {},
          "execution_count": 69
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46cKe32W65Ox"
      },
      "source": [
        "### One-hot encoding\n",
        "\n",
        "If you have a tensor of indicies and would like to one-hot encode it, you can use [`tf.one_hot()`](https://www.tensorflow.org/api_docs/python/tf/one_hot).\n",
        "\n",
        "You should also specify the `depth` parameter (the level which you want to one-hot encode to)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "FlRkMjL-646U",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "57e586aa-c3b6-45af-a068-464b84ad4ca2"
      },
      "source": [
        "# Create a list of indices\n",
        "some_list = [0, 1, 2, 3]\n",
        "\n",
        "# One hot encode them\n",
        "tf.one_hot(some_list, depth=4)"
      ],
      "execution_count": 70,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(4, 4), dtype=float32, numpy=\n",
              "array([[1., 0., 0., 0.],\n",
              "       [0., 1., 0., 0.],\n",
              "       [0., 0., 1., 0.],\n",
              "       [0., 0., 0., 1.]], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 70
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xYxYV0r08THk"
      },
      "source": [
        "You can also specify values for `on_value` and `off_value` instead of the default `0` and `1`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "FZluadm88EcN",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "5f98ee43-cf54-4c96-b466-b85e39d715ff"
      },
      "source": [
        "# Specify custom values for on and off encoding\n",
        "tf.one_hot(some_list, depth=4, on_value=\"We're live!\", off_value=\"Offline\")"
      ],
      "execution_count": 71,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(4, 4), dtype=string, numpy=\n",
              "array([[b\"We're live!\", b'Offline', b'Offline', b'Offline'],\n",
              "       [b'Offline', b\"We're live!\", b'Offline', b'Offline'],\n",
              "       [b'Offline', b'Offline', b\"We're live!\", b'Offline'],\n",
              "       [b'Offline', b'Offline', b'Offline', b\"We're live!\"]], dtype=object)>"
            ]
          },
          "metadata": {},
          "execution_count": 71
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-E-I1jFC84Qi"
      },
      "source": [
        "### Squaring, log, square root\n",
        "\n",
        "Many other common mathematical operations you'd like to perform at some stage, probably exist.\n",
        "\n",
        "Let's take a look at:\n",
        "* [`tf.square()`](https://www.tensorflow.org/api_docs/python/tf/math/square) - get the square of every value in a tensor. \n",
        "* [`tf.sqrt()`](https://www.tensorflow.org/api_docs/python/tf/math/sqrt) - get the squareroot of every value in a tensor (**note:** the elements need to be floats or this will error).\n",
        "* [`tf.math.log()`](https://www.tensorflow.org/api_docs/python/tf/math/log) - get the natural log of every value in a tensor (elements need to floats)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KTOvziCBLqhZ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "10fa84ab-98d0-4bbe-f751-4f94a103e4f0"
      },
      "source": [
        "# Create a new tensor\n",
        "H = tf.constant(np.arange(1, 10))\n",
        "H"
      ],
      "execution_count": 72,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(9,), dtype=int64, numpy=array([1, 2, 3, 4, 5, 6, 7, 8, 9])>"
            ]
          },
          "metadata": {},
          "execution_count": 72
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qvPS3xbk9JBK",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7432fd66-28a6-4ed6-b7dc-fdc198171cec"
      },
      "source": [
        "# Square it\n",
        "tf.square(H)"
      ],
      "execution_count": 73,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(9,), dtype=int64, numpy=array([ 1,  4,  9, 16, 25, 36, 49, 64, 81])>"
            ]
          },
          "metadata": {},
          "execution_count": 73
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "SJibI0GO9uf4",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 353
        },
        "outputId": "18537050-f17e-4f9d-bf6d-c8601384f2a8"
      },
      "source": [
        "# Find the squareroot (will error), needs to be non-integer\n",
        "tf.sqrt(H)"
      ],
      "execution_count": 75,
      "outputs": [
        {
          "output_type": "error",
          "ename": "InvalidArgumentError",
          "evalue": "ignored",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mInvalidArgumentError\u001b[0m                      Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-75-d7db039da8bb>\u001b[0m in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m# Find the squareroot (will error), needs to be non-integer\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mtf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msqrt\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mH\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;32m/usr/local/lib/python3.9/dist-packages/tensorflow/python/util/traceback_utils.py\u001b[0m in \u001b[0;36merror_handler\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m    151\u001b[0m     \u001b[0;32mexcept\u001b[0m \u001b[0mException\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    152\u001b[0m       \u001b[0mfiltered_tb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_process_traceback_frames\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__traceback__\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 153\u001b[0;31m       \u001b[0;32mraise\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mwith_traceback\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfiltered_tb\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    154\u001b[0m     \u001b[0;32mfinally\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    155\u001b[0m       \u001b[0;32mdel\u001b[0m \u001b[0mfiltered_tb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.9/dist-packages/tensorflow/python/framework/ops.py\u001b[0m in \u001b[0;36mraise_from_not_ok_status\u001b[0;34m(e, name)\u001b[0m\n\u001b[1;32m   7260\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mraise_from_not_ok_status\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mname\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   7261\u001b[0m   \u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmessage\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\" name: \"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mname\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mname\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32mNone\u001b[0m \u001b[0;32melse\u001b[0m \u001b[0;34m\"\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 7262\u001b[0;31m   \u001b[0;32mraise\u001b[0m \u001b[0mcore\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_status_to_exception\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0;32mNone\u001b[0m  \u001b[0;31m# pylint: disable=protected-access\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   7263\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   7264\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mInvalidArgumentError\u001b[0m: Value for attr 'T' of int64 is not in the list of allowed values: bfloat16, half, float, double, complex64, complex128\n\t; NodeDef: {{node Sqrt}}; Op<name=Sqrt; signature=x:T -> y:T; attr=T:type,allowed=[DT_BFLOAT16, DT_HALF, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64, DT_COMPLEX128]> [Op:Sqrt]"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zlxRWy6Q-NHK",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f2bc38ee-7af8-4c25-d556-0b464bd871d1"
      },
      "source": [
        "# Change H to float32\n",
        "H = tf.cast(H, dtype=tf.float32)\n",
        "H"
      ],
      "execution_count": 76,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(9,), dtype=float32, numpy=array([1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 76
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "S73eO0p--TtN",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e9204262-c9a3-45bc-ba8e-3436dee76464"
      },
      "source": [
        "# Find the square root\n",
        "tf.sqrt(H)"
      ],
      "execution_count": 77,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(9,), dtype=float32, numpy=\n",
              "array([1.       , 1.4142135, 1.7320508, 2.       , 2.2360678, 2.4494896,\n",
              "       2.6457512, 2.828427 , 3.       ], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 77
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "RyCo55vz9u4f",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a37f7d0a-9f71-43b7-84c3-20a60664bd22"
      },
      "source": [
        "# Find the log (input also needs to be float)\n",
        "tf.math.log(H)"
      ],
      "execution_count": 78,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(9,), dtype=float32, numpy=\n",
              "array([0.       , 0.6931472, 1.0986123, 1.3862944, 1.609438 , 1.7917595,\n",
              "       1.9459102, 2.0794415, 2.1972246], dtype=float32)>"
            ]
          },
          "metadata": {},
          "execution_count": 78
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "urq3bx3l_Y4K"
      },
      "source": [
        "### Manipulating `tf.Variable` tensors\n",
        "\n",
        "Tensors created with `tf.Variable()` can be changed in place using methods such as:\n",
        "\n",
        "* [`.assign()`](https://www.tensorflow.org/api_docs/python/tf/Variable#assign) - assign a different value to a particular index of a variable tensor.\n",
        "* [`.add_assign()`](https://www.tensorflow.org/api_docs/python/tf/Variable#assign_add) - add to an existing value and reassign it at a particular index of a variable tensor.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tV7_uzdR_F4c",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "86c9ccb5-d32f-48a6-d55a-b34053aabc9f"
      },
      "source": [
        "# Create a variable tensor\n",
        "I = tf.Variable(np.arange(0, 5))\n",
        "I"
      ],
      "execution_count": 79,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(5,) dtype=int64, numpy=array([0, 1, 2, 3, 4])>"
            ]
          },
          "metadata": {},
          "execution_count": 79
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ukatOuCG_4CY",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0d36fb98-0c7c-42f7-c439-cdc2c72271d8"
      },
      "source": [
        "# Assign the final value a new value of 50\n",
        "I.assign([0, 1, 2, 3, 50])"
      ],
      "execution_count": 80,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'UnreadVariable' shape=(5,) dtype=int64, numpy=array([ 0,  1,  2,  3, 50])>"
            ]
          },
          "metadata": {},
          "execution_count": 80
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "3r2Pya_vAnLz",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ea862b8c-a8bf-476b-d1b0-4164260c0927"
      },
      "source": [
        "# The change happens in place (the last value is now 50, not 4)\n",
        "I"
      ],
      "execution_count": 81,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(5,) dtype=int64, numpy=array([ 0,  1,  2,  3, 50])>"
            ]
          },
          "metadata": {},
          "execution_count": 81
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gZie_FduAo5O",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ce5e6cf0-224f-4361-e4ad-a3b5725859f9"
      },
      "source": [
        "# Add 10 to every element in I\n",
        "I.assign_add([10, 10, 10, 10, 10])"
      ],
      "execution_count": 82,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'UnreadVariable' shape=(5,) dtype=int64, numpy=array([10, 11, 12, 13, 60])>"
            ]
          },
          "metadata": {},
          "execution_count": 82
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2qXODgVOBDzC",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "c8142fa5-7c51-4ef8-cc0b-2a780d096d19"
      },
      "source": [
        "# Again, the change happens in place\n",
        "I"
      ],
      "execution_count": 83,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Variable 'Variable:0' shape=(5,) dtype=int64, numpy=array([10, 11, 12, 13, 60])>"
            ]
          },
          "metadata": {},
          "execution_count": 83
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2L2IyQhl-Z73"
      },
      "source": [
        "## Tensors and NumPy\n",
        "\n",
        "We've seen some examples of tensors interact with NumPy arrays, such as, using NumPy arrays to create tensors. \n",
        "\n",
        "Tensors can also be converted to NumPy arrays using:\n",
        "\n",
        "* `np.array()` - pass a tensor to convert to an ndarray (NumPy's main datatype).\n",
        "* `tensor.numpy()` - call on a tensor to convert to an ndarray.\n",
        "\n",
        "Doing this is helpful as it makes tensors iterable as well as allows us to use any of NumPy's methods on them."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HLHrij0vBywD",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3fc123c9-c32c-4aac-e61e-900c75fc2a04"
      },
      "source": [
        "# Create a tensor from a NumPy array\n",
        "J = tf.constant(np.array([3., 7., 10.]))\n",
        "J"
      ],
      "execution_count": 84,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(3,), dtype=float64, numpy=array([ 3.,  7., 10.])>"
            ]
          },
          "metadata": {},
          "execution_count": 84
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "P0KBe_FqCKdU",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e93c3a0c-3e7b-4687-ba99-9c84b8e08004"
      },
      "source": [
        "# Convert tensor J to NumPy with np.array()\n",
        "np.array(J), type(np.array(J))"
      ],
      "execution_count": 85,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(array([ 3.,  7., 10.]), numpy.ndarray)"
            ]
          },
          "metadata": {},
          "execution_count": 85
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xxKsJPvSCUPI",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2f661fba-ebb3-4f22-8591-093943268c03"
      },
      "source": [
        "# Convert tensor J to NumPy with .numpy()\n",
        "J.numpy(), type(J.numpy())"
      ],
      "execution_count": 86,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(array([ 3.,  7., 10.]), numpy.ndarray)"
            ]
          },
          "metadata": {},
          "execution_count": 86
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SL4xHtNWDIT5"
      },
      "source": [
        "By default tensors have `dtype=float32`, where as NumPy arrays have `dtype=float64`.\n",
        "\n",
        "This is because neural networks (which are usually built with TensorFlow) can generally work very well with less precision (32-bit rather than 64-bit)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HrQoUeyPCXU9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3b7ae5e1-5fe5-4332-f6c1-09be8f3435f2"
      },
      "source": [
        "# Create a tensor from NumPy and from an array\n",
        "numpy_J = tf.constant(np.array([3., 7., 10.])) # will be float64 (due to NumPy)\n",
        "tensor_J = tf.constant([3., 7., 10.]) # will be float32 (due to being TensorFlow default)\n",
        "numpy_J.dtype, tensor_J.dtype"
      ],
      "execution_count": 87,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(tf.float64, tf.float32)"
            ]
          },
          "metadata": {},
          "execution_count": 87
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_ytLPBWF1wxt"
      },
      "source": [
        "## Using `@tf.function`\n",
        "\n",
        "In your TensorFlow adventures, you might come across Python functions which have the decorator [`@tf.function`](https://www.tensorflow.org/api_docs/python/tf/function).\n",
        "\n",
        "If you aren't sure what Python decorators do, [read RealPython's guide on them](https://realpython.com/primer-on-python-decorators/).\n",
        "\n",
        "But in short, decorators modify a function in one way or another.\n",
        "\n",
        "In the `@tf.function` decorator case, it turns a Python function into a callable TensorFlow graph. Which is a fancy way of saying, if you've written your own Python function, and you decorate it with `@tf.function`, when you export your code (to potentially run on another device), TensorFlow will attempt to convert it into a fast(er) version of itself (by making it part of a computation graph).\n",
        "\n",
        "For more on this, read the [Better performnace with tf.function](https://www.tensorflow.org/guide/function) guide."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "URzFiwPoFDI7",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "65125afb-ff03-47fa-cd8e-033c0aba5eff"
      },
      "source": [
        "# Create a simple function\n",
        "def function(x, y):\n",
        "  return x ** 2 + y\n",
        "\n",
        "x = tf.constant(np.arange(0, 10))\n",
        "y = tf.constant(np.arange(10, 20))\n",
        "function(x, y)"
      ],
      "execution_count": 88,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(10,), dtype=int64, numpy=array([ 10,  12,  16,  22,  30,  40,  52,  66,  82, 100])>"
            ]
          },
          "metadata": {},
          "execution_count": 88
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "EHGbvlkXF7Gs",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1428bb59-5ec5-4bc5-8c72-fb97a7d8a85e"
      },
      "source": [
        "# Create the same function and decorate it with tf.function\n",
        "@tf.function\n",
        "def tf_function(x, y):\n",
        "  return x ** 2 + y\n",
        "\n",
        "tf_function(x, y)"
      ],
      "execution_count": 89,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<tf.Tensor: shape=(10,), dtype=int64, numpy=array([ 10,  12,  16,  22,  30,  40,  52,  66,  82, 100])>"
            ]
          },
          "metadata": {},
          "execution_count": 89
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lsiapEnTGBbH"
      },
      "source": [
        "If you noticed no difference between the above two functions (the decorated one and the non-decorated one) you'd be right.\n",
        "\n",
        "Much of the difference happens behind the scenes. One of the main ones being potential code speed-ups where possible."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y8AQmchkxKDn"
      },
      "source": [
        "## Finding access to GPUs\n",
        "\n",
        "We've mentioned GPUs plenty of times throughout this notebook.\n",
        "\n",
        "So how do you check if you've got one available?\n",
        "\n",
        "You can check if you've got access to a GPU using [`tf.config.list_physical_devices()`](https://www.tensorflow.org/guide/gpu)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "3rFNSeODxi3L",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "87f0a071-24c9-492c-e8f9-0be30cc488b9"
      },
      "source": [
        "print(tf.config.list_physical_devices('GPU'))"
      ],
      "execution_count": 90,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8165PtH8xyq5"
      },
      "source": [
        "If the above outputs an empty array (or nothing), it means you don't have access to a GPU (or at least TensorFlow can't find it).\n",
        "\n",
        "If you're running in Google Colab, you can access a GPU by going to *Runtime -> Change Runtime Type -> Select GPU* (**note:** after doing this your notebook will restart and any variables you've saved will be lost).\n",
        "\n",
        "Once you've changed your runtime type, run the cell below."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iAvMwRbZyULE",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "76f8d50a-94ca-4f83-ec4c-196826e898df"
      },
      "source": [
        "import tensorflow as tf\n",
        "print(tf.config.list_physical_devices('GPU'))"
      ],
      "execution_count": 91,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "J3yu0LKiyZlJ"
      },
      "source": [
        "If you've got access to a GPU, the cell above should output something like:\n",
        "\n",
        "`[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]`\n",
        "\n",
        "You can also find information about your GPU using `!nvidia-smi`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yOuVvG5kyefS",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "121bba78-489f-4804-c861-1952d7c82751"
      },
      "source": [
        "!nvidia-smi"
      ],
      "execution_count": 92,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Tue Apr 25 05:24:15 2023       \n",
            "+-----------------------------------------------------------------------------+\n",
            "| NVIDIA-SMI 525.85.12    Driver Version: 525.85.12    CUDA Version: 12.0     |\n",
            "|-------------------------------+----------------------+----------------------+\n",
            "| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n",
            "| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n",
            "|                               |                      |               MIG M. |\n",
            "|===============================+======================+======================|\n",
            "|   0  NVIDIA A100-SXM...  Off  | 00000000:00:04.0 Off |                    0 |\n",
            "| N/A   32C    P0    51W / 400W |    693MiB / 40960MiB |      0%      Default |\n",
            "|                               |                      |             Disabled |\n",
            "+-------------------------------+----------------------+----------------------+\n",
            "                                                                               \n",
            "+-----------------------------------------------------------------------------+\n",
            "| Processes:                                                                  |\n",
            "|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n",
            "|        ID   ID                                                   Usage      |\n",
            "|=============================================================================|\n",
            "+-----------------------------------------------------------------------------+\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pER7mLFezV9u"
      },
      "source": [
        "> 🔑 **Note:** If you have access to a GPU, TensorFlow will automatically use it whenever possible."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HcCZxK61VIv0"
      },
      "source": [
        "## 🛠 Exercises\n",
        "\n",
        "1. Create a vector, scalar, matrix and tensor with values of your choosing using `tf.constant()`.\n",
        "2. Find the shape, rank and size of the tensors you created in 1.\n",
        "3. Create two tensors containing random values between 0 and 1 with shape `[5, 300]`.\n",
        "4. Multiply the two tensors you created in 3 using matrix multiplication.\n",
        "5. Multiply the two tensors you created in 3 using dot product.\n",
        "6. Create a tensor with random values between 0 and 1 with shape `[224, 224, 3]`.\n",
        "7. Find the min and max values of the tensor you created in 6.\n",
        "8. Created a tensor with random values of shape `[1, 224, 224, 3]` then squeeze it to change the shape to `[224, 224, 3]`.\n",
        "9. Create a tensor with shape `[10]` using your own choice of values, then find the index which has the maximum value.\n",
        "10. One-hot encode the tensor you created in 9."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EgHK5CjY3oVX"
      },
      "source": [
        "## 📖 Extra-curriculum\n",
        "\n",
        "* Read through the [list of TensorFlow Python APIs](https://www.tensorflow.org/api_docs/python/), pick one we haven't gone through in this notebook, reverse engineer it (write out the documentation code for yourself) and figure out what it does.\n",
        "* Try to create a series of tensor functions to calculate your most recent grocery bill (it's okay if you don't use the names of the items, just the price in numerical form).\n",
        "  * How would you calculate your grocery bill for the month and for the year using tensors?\n",
        "* Go through the [TensorFlow 2.x quick start for beginners](https://www.tensorflow.org/tutorials/quickstart/beginner) tutorial (be sure to type out all of the code yourself, even if you don't understand it).\n",
        "  * Are there any functions we used in here that match what's used in there? Which are the same? Which haven't you seen before?\n",
        "* Watch the video [\"What's a tensor?\"](https://www.youtube.com/watch?v=f5liqUk0ZTw) - a great visual introduction to many of the concepts we've covered in this notebook."
      ]
    }
  ]
}